import React, { useMemo } from 'react';
import { show_mt, loc, HandView, obj_str, no_del, PanelFind, filter_row, BtTxt, useCmd, useHigh, Btn, GridTable } from 'sui';
import { useAccess } from 'cache';
import { get_ck } from 'stuff/cmd';

const UserView = () => {
    const [high] = useHigh(140, 100);
    const [no_acc] = useAccess();
    const umd = useCmd("file/list/oiltp");

    const getRow = useMemo(() => {
        const lst = ["sn", "name"];
        return filter_row(umd.value, lst, umd.filter);
    }, [umd.value, umd.filter]);

    const act = {
        "add": (v, h) => umd.update("file/md/oiltp", {v: v, sn: obj_str(v, "sn")}, h),
        "edit": (v, h) => umd.update("file/md/oiltp", {v: v, sn: obj_str(v, "sn")}, h),
    };

    const col = [
        {sn: "sn", name: loc("l_495"), tp: "string"},
        {sn: "name", name: loc("l_189"), tp: "string"},
        {sn: "level", name: loc("l_114"), tp: "num"},
        {sn: "unit", name: loc("l_122"), tp: "string"},
        {sn: "box", name: loc("l_123"), tp: "string"},
    ];

    if (umd.isFin("edit") || umd.isFin("add")) {
        return <HandView umd={umd} title={loc("l_811")} act={act} col={col} ck={get_ck(umd.cur, umd.value, col)}/>;
    }

    const hDel = (val) => {
        if (no_del()) {
            return;
        }

        umd.update("file/rm/oiltp", {sn: obj_str(val, "sn")});
    };

    const getCol = () => {
        const tmp = [
            {name: loc("l_193"), key: 'index', width: 70, frozen: true},
            {name: loc("l_238"), key: 'e_opt', width: 120, frozen: true, formatter: (props) => {
                const d = props.row;
                return (
                    <div className="inline-flex">
                        <BtTxt hcmd={() => umd.pact(null, d, "edit")} disabled={no_acc("ue")}>{loc("l_235")}</BtTxt>
                        <BtTxt hcmd={() => hDel(d)} disabled={no_acc("ue")}>{loc("l_237")}</BtTxt>
                    </div>
                );
            }},
        ];

        col.forEach(d => show_mt(tmp, d, 200));

        return tmp;
    };

    const Right = () => <Btn color="green" hcmd={() => umd.pact(null, null, "add")} className="ml-4" disabled={no_acc("ue")}>{loc("l_239")}</Btn>;

    return (
        <div className="flex flex-col">
            <PanelFind left={loc("l_109")} right={<Right/>} hcmd={umd.setFilter}/>
            <GridTable high={high} col={getCol()} row={getRow}/>
        </div>
    );
};

export {UserView};
